package com.lin.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.lin.utils.JdbcUtils;
import com.lin.vo.User;

public class UserDaoImpl implements IUserDao {

	@Override
	public void save(User user) {
		QueryRunner queryRunner=new QueryRunner(JdbcUtils.getDataSource());
		String sql="INSERT INTO user VALUES(?,?,?,?,?,?)";
		Object [] params={user.getUid(),user.getUsername(),user.getPassword(),user.getEmail(),user.getState(),user.getCode()};
		try {
			queryRunner.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

	@Override
	public User findByCodeUser(String code) {
		QueryRunner queryRunner=new QueryRunner(JdbcUtils.getDataSource());
		String sql="SELECT *from user WHERE code = ?";
		User user;
		try {
			user = queryRunner.query(sql, new BeanHandler<>(User.class), code);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return user;
	}

	@Override
	public void update(User user) {
		QueryRunner queryRunner=new QueryRunner(JdbcUtils.getDataSource());
		String sql = "UPDATE user SET username = ?,password = ?,email = ?,state = ?,code = ? where uid = ?";
		Object[] params = {user.getUsername(), user.getPassword(), user.getEmail(), user.getState(),
				user.getCode(),user.getUid()};
		try {
			queryRunner.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		
	}

	@Override
	public boolean validateAjaxUserName(String userName) {
		QueryRunner queryRunner=new QueryRunner(JdbcUtils.getDataSource());
		String sql="SELECT COUNT(1) FROM user  WHERE username = ?";
		Number num;
		try {
			num = (Number) queryRunner.query(sql, new ScalarHandler(),userName);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return num.intValue() == 0;
	}

	@Override
	public User login(User user) {	
		QueryRunner queryRunner=new QueryRunner(JdbcUtils.getDataSource());
		String sql="SELECT *FROM user WHERE username=? AND password = ?";
		User exitUser;
		try {
			exitUser = queryRunner.query(sql, new BeanHandler<>(User.class), user.getUsername(),user.getPassword());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return exitUser;
	}



}
